using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Diagnostics;
using BackupManager.Tasks;
using System.Net;
using System.IO;

namespace WebRole
{
    public class WebRole : RoleEntryPoint
    {
        private TaskManager _TaskManager;

        public override bool OnStart()
        {
            // To enable the AzureLocalStorageTraceListner, uncomment relevent section in the web.config  
            DiagnosticMonitorConfiguration diagnosticConfig = DiagnosticMonitor.GetDefaultInitialConfiguration();
            diagnosticConfig.Directories.ScheduledTransferPeriod = TimeSpan.FromMinutes(15);
            diagnosticConfig.Directories.DataSources.Add(AzureLocalStorageTraceListener.GetLogDirectory());

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            InstallDacFramework();

            return base.OnStart();
        }

        private void InstallDacFramework()
        {
            var localStoragePath = RoleEnvironment.GetLocalResource("BackupLocalStorage").RootPath;
            var setupPath = Path.Combine(localStoragePath, "Setup");
            if (!Directory.Exists(setupPath))
            {
                Directory.CreateDirectory(setupPath);
            }

            DownloadAndInstall(setupPath, "http://download.microsoft.com/download/4/B/1/4B1E9B0E-A4F3-4715-B417-31C82302A70A/ENU/x86/SQLSysClrTypes.msi");
            DownloadAndInstall(setupPath, "http://download.microsoft.com/download/4/B/1/4B1E9B0E-A4F3-4715-B417-31C82302A70A/ENU/x86/SqlDom.msi");
            DownloadAndInstall(setupPath, "http://download.microsoft.com/download/4/B/1/4B1E9B0E-A4F3-4715-B417-31C82302A70A/ENU/x86/DACFramework.msi");

            DownloadAndInstall(setupPath, "http://download.microsoft.com/download/4/B/1/4B1E9B0E-A4F3-4715-B417-31C82302A70A/ENU/x64/SQLSysClrTypes.msi");
            DownloadAndInstall(setupPath, "http://download.microsoft.com/download/4/B/1/4B1E9B0E-A4F3-4715-B417-31C82302A70A/ENU/x64/SqlDom.msi");
            DownloadAndInstall(setupPath, "http://download.microsoft.com/download/4/B/1/4B1E9B0E-A4F3-4715-B417-31C82302A70A/ENU/x64/DACFramework.msi");
        }

        private void DownloadAndInstall(string setupPath, string url)
        {
            var fileName = url.Split('/').Last();
            var filePath = Path.Combine(setupPath, fileName);
            using (var webClient = new WebClient())
            {
                webClient.DownloadFile(url, filePath);
            }
            InstallMsiFile(filePath);
        }

        private void InstallMsiFile(string msiPath)
        {
            try
            {
                Process.Start("msiexec.exe", Environment.ExpandEnvironmentVariables(string.Format(@"/qn /i  {0} /l*v {0}.txt", msiPath))).WaitForExit();
            }
            catch { }
        }

        public override void Run()
        {
            _TaskManager = new TaskManager();
            _TaskManager.Start();
            base.Run();
        }

        public override void OnStop()
        {
            _TaskManager.Stop();
            base.OnStop();
        }
    }
}
